<template>
	<BackgroundImage>
		<!-- 顶部导航 -->
		<TopNavigation title="赛事业务查询" backText="首页" />
		
		<view class="match-query-container">

		<!-- 统计卡片 -->
		<view class="stats-section">
			<DataBox>
				<view class="stats-content">
					<view class="stats-item">
						<text class="stats-label">总赛事数 >></text>
						<text class="stats-number">{{ matchStats.totalMatches }}</text>
					</view>
					<view class="stats-item">
						<text class="stats-label">进行中赛事 >></text>
						<text class="stats-number">{{ matchStats.activeMatches }}</text>
					</view>
				</view>
			</DataBox>
		</view>

		<!-- 查询条件 -->
		<view class="query-section">
			<view class="query-card">
				<view class="query-header">
					<!-- <text class="section-title">查询条件</text> -->
					<view class="header-actions">
						<button class="init-btn" @click="initMatch">初始化赛事</button>
						<button class="init-schedule-btn" @click="initSchedule">初始化赛程</button>
						<button class="manage-btn" @click="goToManageModels">模式管理</button>
						<button class="create-btn" @click="goToCreateMatch">创建赛事</button>
					</view>
				</view>
				<!--
        <view class="query-form">
          <view class="form-item">
            <text class="form-label">赛事名称</text>
            <input 
              class="form-input" 
              v-model="queryParams.name" 
              placeholder="请输入赛事名称"
            />
          </view>
          <view class="form-item">
            <text class="form-label">状态</text>
            <picker 
              class="form-picker" 
              :value="queryParams.statusIndex" 
              :range="statusOptions" 
              @change="onStatusChange"
            >
              <text class="picker-text">{{ statusOptions[queryParams.statusIndex] }}</text>
            </picker>
          </view>
          <view class="form-item">
            <text class="form-label">时间范围</text>
            <view class="date-range">
              <picker 
                class="date-picker" 
                mode="date" 
                :value="queryParams.startDate" 
                @change="onStartDateChange"
              >
                <text class="picker-text">{{ queryParams.startDate || '开始日期' }}</text>
              </picker>
              <text class="date-separator">至</text>
              <picker 
                class="date-picker" 
                mode="date" 
                :value="queryParams.endDate" 
                @change="onEndDateChange"
              >
                <text class="picker-text">{{ queryParams.endDate || '结束日期' }}</text>
              </picker>
            </view>
          </view>
          <view class="form-buttons">
            <button class="query-btn" @click="queryMatches">查询</button>
            <button class="reset-btn" @click="resetQuery">重置</button>
          </view>
        </view>
        -->
			</view>
		</view>

		<!-- 赛事列表 -->
		<view class="match-list-section">
			<view class="list-header">
				<text class="section-title">赛事列表</text>
				<text class="list-count">共 {{ matchList.length }} 个赛事</text>
			</view>

			<view class="match-list">
				<view class="match-item" v-for="match in matchList" :key="match.id" @click="showMatchDetail(match)">
					<view class="match-header">
						<text class="match-name">{{ match.name }}</text>
						<view class="match-status" :class="getStatusClass(match.status)">
							{{ getStatusText(match.status) }}
						</view>
					</view>

					<view class="match-info">
						<view class="info-row">
							<text class="info-label">赛事ID:</text>
							<text class="info-value">{{ match.id }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">创建者:</text>
							<text class="info-value">{{ match.createUserID }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">赞助商:</text>
							<text class="info-value">{{ match.sponsor || '无' }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">开始时间:</text>
							<text class="info-value">{{ formatDate(match.startTime) }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">结束时间:</text>
							<text class="info-value">{{ formatDate(match.endTime) }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">赛程数量:</text>
							<text class="info-value schedule-count">{{ match.scheduleCount || 0 }} 个</text>
						</view>
					</view>

					<view class="match-actions">
						<button class="action-btn" @click.stop="viewSchedules(match)">查看赛程</button>
						<button class="action-btn" @click.stop="viewMatchModels(match)">比赛模式</button>
						<button class="action-btn" @click.stop="editMatch(match)">编辑</button>
					</view>
				</view>
			</view>

			<!-- 分页 -->
			<view class="pagination" v-if="totalPages > 1">
				<button class="page-btn" :disabled="currentPage <= 1" @click="changePage(currentPage - 1)">
					上一页
				</button>
				<text class="page-info">{{ currentPage }} / {{ totalPages }}</text>
				<button class="page-btn" :disabled="currentPage >= totalPages" @click="changePage(currentPage + 1)">
					下一页
				</button>
			</view>
		</view>

		<!-- 加载状态 -->
		<view class="loading-overlay" v-if="loading">
			<view class="loading-content">
				<view class="loading-spinner"></view>
				<text class="loading-text">加载中...</text>
			</view>
		</view>
	</view>
	</BackgroundImage>
</template>

<script setup>
	import BackgroundImage from "@/components/BackgroundImage.vue";
	import TopNavigation from "@/components/UiView/TopNavigation.vue";
	import DataBox from "@/components/DataBox.vue";
	import {
		ref,
		onMounted
	} from 'vue'
	import {
		MatchAPI,
		BattleAPI
	} from '@/api/battle.js'

	// 响应式数据
	const loading = ref(false)
	const matchList = ref([])

	// 统计数据
	const matchStats = ref({
		totalMatches: 0,
		totalSchedules: 0,
		activeMatches: 0
	})

	// 查询参数
	const queryParams = ref({
		name: '',
		status: '',
		statusIndex: 0,
		startDate: '',
		endDate: '',
		pageNum: 0,
		pageSize: 10
	})

	// 分页信息
	const currentPage = ref(1)
	const totalPages = ref(1)

	// 状态选项
	const statusOptions = ['全部', '待开始', '进行中', '已结束']

	// 状态映射
	const statusMap = {
		0: '待开始',
		1: '进行中',
		2: '已结束'
	}

	// 状态样式映射
	const statusClassMap = {
		0: 'status-pending',
		1: 'status-active',
		2: 'status-finished'
	}

	// 获取状态文本
	const getStatusText = (status) => {
		return statusMap[status] || '未知'
	}

	// 获取状态样式
	const getStatusClass = (status) => {
		return statusClassMap[status] || 'status-unknown'
	}

	// 格式化日期
	const formatDate = (timestamp) => {
		if (!timestamp) return '未设置'
		const date = new Date(timestamp)
		return date.toLocaleString('zh-CN')
	}

	// 状态选择变化
	const onStatusChange = (e) => {
		const index = e.detail.value
		queryParams.value.statusIndex = index
		queryParams.value.status = index === 0 ? '' : index - 1
	}

	// 开始日期变化
	const onStartDateChange = (e) => {
		queryParams.value.startDate = e.detail.value
	}

	// 结束日期变化
	const onEndDateChange = (e) => {
		queryParams.value.endDate = e.detail.value
	}

	// 查询赛事
	const queryMatches = async () => {
		loading.value = true
		try {
			// 构建查询参数
			const params = {
				pageNum: queryParams.value.pageNum,
				pageSize: queryParams.value.pageSize
			}

			if (queryParams.value.name) {
				params.name = queryParams.value.name
			}

			if (queryParams.value.status !== '') {
				params.status = queryParams.value.status
			}

			if (queryParams.value.startDate) {
				params.startTime = new Date(queryParams.value.startDate).getTime()
			}

			if (queryParams.value.endDate) {
				params.endTime = new Date(queryParams.value.endDate + ' 23:59:59').getTime()
			}

			const result = await MatchAPI.page(params)
			console.log('赛事查询API返回结果:', result)

			if (result.code === 0) {
				matchList.value = result.data || []
				totalPages.value = result.data && result.data.length > 0 ? currentPage.value : 1
				currentPage.value = queryParams.value.pageNum + 1

				// 更新统计数据
				updateStats()

				uni.showToast({
					title: '查询成功',
					icon: 'success'
				})
			} else {
				throw new Error(result.msg || '查询失败')
			}
		} catch (error) {
			console.error('查询赛事失败:', error)
			uni.showToast({
				title: error.message || '查询失败',
				icon: 'none'
			})
		} finally {
			loading.value = false
		}
	}

	// 重置查询
	const resetQuery = () => {
		queryParams.value = {
			name: '',
			status: '',
			statusIndex: 0,
			startDate: '',
			endDate: '',
			pageNum: 0,
			pageSize: 10
		}
		queryMatches()
	}

	// 切换页面
	const changePage = (page) => {
		if (page < 1 || page > totalPages.value) return

		queryParams.value.pageNum = page - 1
		queryMatches()
	}

	// 显示赛事详情
	const showMatchDetail = (match) => {
		// 这里可以跳转到详情页面或显示详情弹窗
		uni.showModal({
			title: '赛事详情',
			content: `赛事名称: ${match.name}\n赛事ID: ${match.id}\n描述: ${match.desc || '无'}`,
			showCancel: false
		})
	}

	// 查看赛程
	const viewSchedules = (match) => {
		uni.navigateTo({
			url: `/views/schedule-query?matchId=${match.id}&matchName=${encodeURIComponent(match.name)}`
		})
	}

	// 查看比赛模式
	const viewMatchModels = (match) => {
		uni.navigateTo({
			url: `/views/match-model-manage?matchId=${match.id}&matchName=${encodeURIComponent(match.name)}`
		})
	}

	// 编辑赛事
	const editMatch = (match) => {
		// 这里可以跳转到编辑页面
		uni.showModal({
			title: '编辑赛事',
			content: `是否要编辑赛事 "${match.name}"？`,
			success: (res) => {
				if (res.confirm) {
					// 跳转到编辑页面
					uni.navigateTo({
						url: `/views/match-edit?matchId=${match.id}`
					})
				}
			}
		})
	}

	// 跳转到创建赛事页面
	const goToCreateMatch = () => {
		uni.navigateTo({
			url: '/views/match-create'
		})
	}

	// 初始化赛事
	const initMatch = async () => {
		// 显示确认对话框
		uni.showModal({
			title: '初始化赛事',
			content: '确定要初始化所有赛事吗？这将重置赛事状态。',
			success: async (res) => {
				if (res.confirm) {
					loading.value = true
					try {
						console.log('开始初始化赛事...')

						// 调用BattleAPI.initMatch方法
						const result = await BattleAPI.initMatch({
							// 这里可以根据需要传递参数
							// 如果不传递具体参数，API会处理默认的初始化逻辑
						})

						console.log('初始化赛事API返回结果:', result)

						if (result.code === 0) {
							uni.showToast({
								title: '赛事初始化成功',
								icon: 'success'
							})

							// 重新加载赛事列表
							queryMatches()
						} else {
							throw new Error(result.msg || '初始化失败')
						}
					} catch (error) {
						console.error('初始化赛事失败:', error)
						uni.showToast({
							title: error.message || '初始化失败',
							icon: 'none'
						})
					} finally {
						loading.value = false
					}
				}
			}
		})
	}

	// 初始化赛程
	const initSchedule = async () => {
		// 显示确认对话框
		uni.showModal({
			title: '初始化赛程',
			content: '确定要初始化所有赛程吗？这将重置赛程状态。',
			success: async (res) => {
				if (res.confirm) {
					loading.value = true
					try {
						console.log('开始初始化赛程...')

						// 调用BattleAPI.initSchdule方法
						const result = await BattleAPI.initSchdule({
							// 这里可以根据需要传递参数
							// 如果不传递具体参数，API会处理默认的初始化逻辑
						})

						console.log('初始化赛程API返回结果:', result)

						if (result.code === 0) {
							uni.showToast({
								title: '赛程初始化成功',
								icon: 'success'
							})

							// 重新加载赛事列表
							queryMatches()
						} else {
							throw new Error(result.msg || '初始化失败')
						}
					} catch (error) {
						console.error('初始化赛程失败:', error)
						uni.showToast({
							title: error.message || '初始化失败',
							icon: 'none'
						})
					} finally {
						loading.value = false
					}
				}
			}
		})
	}

	// 跳转到模式管理页面
	const goToManageModels = () => {
		uni.navigateTo({
			url: '/views/match-model-manage'
		})
	}

	// 更新统计数据
	const updateStats = () => {
		const totalMatches = matchList.value.length
		const activeMatches = matchList.value.filter(match => match.status === 1).length
		const totalSchedules = matchList.value.reduce((sum, match) => sum + (match.scheduleCount || 0), 0)

		matchStats.value = {
			totalMatches,
			totalSchedules,
			activeMatches
		}
	}

	// 页面加载时执行查询
	onMounted(() => {
		queryMatches()
	})
</script>

<style lang="scss" scoped>
	.match-query-container {
		min-height: 100vh;
		padding: 40rpx;
		padding-top: 140rpx; // 为顶部导航栏留出空间
		position: relative;
	}

	.stats-section {
		margin-bottom: 40rpx;

		.stats-content {
			display: flex;
			justify-content: space-around;

			.stats-item {
				text-align: left;

			.stats-label {
				display: block;
				font-size: 24rpx;
				color: rgba(255, 255, 255, 0.6);
				margin-bottom: 15rpx;
				font-weight: 500;
			}

				.stats-number {
					display: block;
					font-size: 56rpx;
					font-weight: bold;
					color: #ffffff;
					text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
				}
			}
		}
	}

	.query-section {
		margin-bottom: 40rpx;

		.query-card {
			background: rgba(255, 255, 255, 0.95);
			border-radius: 20rpx;
			padding: 40rpx;
			box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);

			.query-header {
				display: flex;
				justify-content: flex-end;
				align-items: center;
				margin-bottom: 30rpx;

				.section-title {
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
				}

				.header-actions {
					display: flex;
					gap: 15rpx;
					flex-wrap: wrap;
					justify-content: flex-end;

					.init-btn,
					.init-schedule-btn,
					.manage-btn,
					.create-btn {
						height: 60rpx;
						padding: 0 20rpx;
						border: none;
						border-radius: 12rpx;
						color: #fff;
						font-size: 24rpx;
						font-weight: bold;
						white-space: nowrap;
						min-width: auto;
						flex-shrink: 0;
					}

					.init-btn {
						background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
					}

					.init-schedule-btn {
						background: linear-gradient(135deg, #fd7e14 0%, #e55a00 100%);
					}

					.manage-btn,
					.create-btn {
						background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
					}
				}
			}

			.query-form {
				.form-item {
					margin-bottom: 30rpx;

					.form-label {
						display: block;
						font-size: 28rpx;
						color: #333;
						margin-bottom: 15rpx;
					}

					.form-input {
						width: 100%;
						height: 80rpx;
						border: 2rpx solid #eee;
						border-radius: 12rpx;
						padding: 0 20rpx;
						font-size: 28rpx;
						background: #fff;
						box-sizing: border-box;
					}

					.form-picker {
						width: 100%;
						height: 80rpx;
						border: 2rpx solid #eee;
						border-radius: 12rpx;
						padding: 0 20rpx;
						background: #fff;
						display: flex;
						align-items: center;
						box-sizing: border-box;

						.picker-text {
							font-size: 28rpx;
							color: #333;
						}
					}

					.date-range {
						display: flex;
						align-items: center;
						gap: 20rpx;

						.date-picker {
							flex: 1;
							height: 80rpx;
							border: 2rpx solid #eee;
							border-radius: 12rpx;
							padding: 0 20rpx;
							background: #fff;
							display: flex;
							align-items: center;
							box-sizing: border-box;

							.picker-text {
								font-size: 28rpx;
								color: #333;
							}
						}

						.date-separator {
							font-size: 28rpx;
							color: #666;
							flex-shrink: 0;
						}
					}
				}

				.form-buttons {
					display: flex;
					gap: 20rpx;

					.query-btn,
					.reset-btn {
						flex: 1;
						height: 80rpx;
						border: none;
						border-radius: 12rpx;
						font-size: 28rpx;
						font-weight: bold;

						&.query-btn {
							background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
							color: #fff;
						}

						&.reset-btn {
							background: #f8f9fa;
							color: #666;
							border: 2rpx solid #eee;
						}
					}
				}
			}
		}
	}

	.match-list-section {
		.list-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 30rpx;

			.section-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #fff;
			}

			.list-count {
				font-size: 24rpx;
				color: rgba(255, 255, 255, 0.8);
			}
		}

		.match-list {
			.match-item {
				background: rgba(255, 255, 255, 0.95);
				border-radius: 20rpx;
				padding: 40rpx;
				margin-bottom: 30rpx;
				box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);

				.match-header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 30rpx;

					.match-name {
						font-size: 32rpx;
						font-weight: bold;
						color: #333;
					}

					.match-status {
						padding: 8rpx 20rpx;
						border-radius: 20rpx;
						font-size: 24rpx;
						font-weight: bold;

						&.status-pending {
							background: #fff3cd;
							color: #856404;
						}

						&.status-active {
							background: #d4edda;
							color: #155724;
						}

						&.status-finished {
							background: #f8d7da;
							color: #721c24;
						}
					}
				}

				.match-info {
					margin-bottom: 30rpx;

					.info-row {
						display: flex;
						margin-bottom: 15rpx;

						.info-label {
							width: 160rpx;
							font-size: 26rpx;
							color: #666;
						}

						.info-value {
							flex: 1;
							font-size: 26rpx;
							color: #333;

							&.schedule-count {
								color: #667eea;
								font-weight: bold;
							}
						}
					}
				}

				.match-actions {
					display: flex;
					gap: 15rpx;

					.action-btn {
						flex: 1;
						height: 60rpx;
						border: none;
						border-radius: 12rpx;
						font-size: 24rpx;
						background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
						color: #fff;
					}
				}
			}
		}

		.pagination {
			display: flex;
			justify-content: center;
			align-items: center;
			gap: 30rpx;
			margin-top: 40rpx;

			.page-btn {
				height: 60rpx;
				padding: 0 30rpx;
				border: none;
				border-radius: 12rpx;
				font-size: 26rpx;
				background: rgba(255, 255, 255, 0.9);
				color: #333;

				&:disabled {
					opacity: 0.5;
				}
			}

			.page-info {
				font-size: 26rpx;
				color: #fff;
			}
		}
	}

	.loading-overlay {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 9999;

		.loading-content {
			background: #fff;
			border-radius: 20rpx;
			padding: 60rpx;
			display: flex;
			flex-direction: column;
			align-items: center;

			.loading-spinner {
				width: 60rpx;
				height: 60rpx;
				border: 4rpx solid #f3f3f3;
				border-top: 4rpx solid #667eea;
				border-radius: 50%;
				animation: spin 1s linear infinite;
				margin-bottom: 20rpx;
			}

			.loading-text {
				font-size: 28rpx;
				color: #666;
			}
		}
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}
</style>